<template>
  <div class="wrap" @contextmenu.prevent>
    <div class="player-main-kpb">
      <div id="player-kpb" />
    </div>
    <div class="chat-main">
      <div v-if="showRTC" id="local" />
      <div class="chat-body">
        <div class="rtc-btn">
          <el-button v-if="showApply" size="mini" type="success" @click="joinChannel"> 申请连麦 </el-button>
          <el-button v-if="showCancel" size="mini" type="warning" @click="cancelJoinChannel"> 取消连麦 </el-button>
          <el-button v-if="showStop" size="mini" type="danger" @click="leaveChannel"> 结束连麦 </el-button>
        </div>
        <div id="chatroom" />
      </div>
    </div>
  </div>
</template>
<script>
  // 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
  // 例如：import 组件名称 from '组件路径';
  export default {
    name: "",
    // import引入的组件需要注入到对象中才能使用
    components: {},
    // 引入混淆
    mixins: [],
    // 引入组件
    props: {},
    data() {
      // 这里存放数据
      return {
        showRTC: false,
        showApply: false,
        showCancel: false,
        showStop: false,
        channelId: null,
        appId: null,
        userId: null,
        userName: null,
        pic: null,
        role: null,
        liveSign: null,
        timestamp: null,
        token: null,
        mediaChannelKey: null
      };
    },
    // 监听属性 类似于data概念
    computed: {},
    // 监控data中的数据变化
    watch: {},
    // 生命周期 - 创建完成（可以访问当前this实例）
    created() {},
    // 生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {
      this.initMsg();
    },
    // 生命周期 - 创建之前
    beforeCreate() {},
    // 生命周期 - 挂载之前
    beforeMount() {},
    // 生命周期 - 更新之前
    beforeUpdate() {},
    // 生命周期 - 更新之后
    updated() {},
    // 生命周期 - 销毁之前
    beforeDestroy() {},
    // 生命周期 - 销毁完成
    destroyed() {},
    // 如果页面有keep-alive缓存功能，这个函数会触发
    activated() {},
    // 方法集合
    methods: {
      // liveSign
      // 初始化数据
      initMsg() {
        this.$ajax
          // .get(this.api.getLiveInitUrl + this.$route.query.id)
          .get(this.api.getLiveInitUrl, {
            params: {
              liveSign: decodeURIComponent(this.$route.query.id)
            }
          })
          .then((res) => {
            console.log("res", res);
            if (res.data.success) {
              // appId: "fp8q9dp74d";
              // channelNO: "2643269";
              // liveSign: "39456F62FA0EE584790307967C5B7B09";
              // role: "viewer";
              // timestamp: 1635575328091;
              // userId: "111222333";
              // userName: "test";
              const response = res.data.data;
              this.channelId = response.channelNO;
              this.appId = response.appId;
              this.userId = response.userId;
              this.userName = response.userName;
              // this.pic = response.pic;
              this.role = response.role;
              this.liveSign = response.liveSign;
              this.timestamp = response.timestamp;
              // this.token = response.token;
              // this.mediaChannelKey = response.mediaChannelKey;
              // this.initLive();
              this.initPolyvFn();
            } else {
              this.$message.error("获取数据失败");
            }
          });
      },
      initPolyvFn() {
        // var liveSdk = new PolyvLiveSdk({
        //   channelId: channelId,
        //   sign: sign, // 频道验证签名
        //   timestamp: timestamp, // 毫秒级时间戳
        //   appId: appId, // polyv 后台的appId
        //   user: {
        //     userId: userId,
        //     userName: "polyv-test",
        //     pic: "//livestatic.videocc.net/assets/wimages/missing_face.png",
        //   },
        // });
        // 全局注册rtc
        // window.rtc = new PolyvRTCWebSDK({
        //   roomId: this.channelId,
        //   // socket: chatroom.chat.socket, // 传入socketio实例
        //   userId: this.userId,
        //   nick: this.userName,
        //   pic: this.pic,
        // });
        const liveSdk = new PolyvLiveSdk({
          channelId: this.channelId,
          sign: this.liveSign, // 频道验证签名
          timestamp: this.timestamp, // 毫秒级时间戳
          appId: this.appId, // polyv 后台的appId
          // socket: chatroom.chat.socket,
          user: {
            userId: this.userId,
            userName: this.userName,
            pic: this.pic
          }
        });
        liveSdk.on(PolyvLiveSdk.EVENTS.CHANNEL_DATA_INIT, (event, data) => {
          liveSdk.setupPlayer({
            el: "#player-kpb", // 讲师区域元素，也就是第 2 步中创建的 id 为 player 的元素
            type: "auto" // 根据频道实际设置自动选择播放类型
          });
        });
        // this.initSDK();
      },
      // 初始化SDK
      initSDK() {
        // 讲师开启连麦，显示申请按钮
        rtc.on("OPEN_MICROPHONE", (evt) => {
          this.showApply = true;
        });
        rtc.on("ALLOW_MICROPHONE", (evt) => {
          this.showRTC = true;
          console.log(`开始加入连麦，频道为 ${evt.roomId}`);
        });
        // 初始化本地流成功
        rtc.on("INIT_LOCALSTREAM_SUCCESS", (evt) => {
          console.log("初始化本地流成功");
        });
        // 初始化本地流失败
        rtc.on("INIT_LOCALSTREAM_ERROR", (evt, error) => {
          console.log(evt.message);
          console.log(error);
        });
        // 推流成功
        rtc.on("PUBLIC_STREAM_SUCCESS", (evt) => {
          console.log("推流成功");
        });
        // 推流失败
        rtc.on("PUBLIC_STREAM_ERROR", (evt, error) => {
          console.log(error);
        });
        // 准备推流，设置推流参数
        rtc.on("INIT_LOCAL_STREAM_READY", (evt) => {
          console.log(`准备推流，通话类型为${evt.type}`);
          evt.init({
            element: document.getElementById("local"),
            control: true,
            profile: "240p"
          });
        });
        // 推流成功隐藏申请与取消申请按钮，显示挂断按钮
        rtc.on("PUBLIC_STREAM_SUCCESS", (evt) => {
          this.showApply = false;
          this.showCancel = false;
          this.showStop = true;
        });
        // 申请连麦超时
        rtc.on("JOIN_CHANNEL_TIMEOUT", (evt) => {
          alert("申请连麦超时，请重新申请");
        });
        // 讲师关闭语音通话，两个按钮隐藏
        rtc.on("CLOSE_MICROPHONE", (evt) => {
          this.showRTC = false;
          this.showApply = false;
          this.showCancel = false;
          this.showStop = false;
        });
        // 被挂断
        rtc.on("CLIENT_BANNED", (evt) => {
          this.showApply = true;
          this.showRTC = false;
          this.showCancel = false;
          this.showStop = false;
        });
        rtc.on("LOCAL_MUTE_VIDEO", (evt) => {
          console.log("关闭视频轨道");
        });
      },
      // 初始化播放器
      initLive() {
        const vueObj = this;
        // let chatroom = new PolyvChatRoom({
        //   roomId: vueObj.channelId, // 直播频道号
        //   userId: vueObj.userId, // 用户唯一id
        //   nick: vueObj.userName, // 用户昵称，默认为‘游客’
        //   pic: vueObj.pic, // 用户头像
        //   token: vueObj.token, // 校验码
        //   version: "2.0", // 版本号，默认为2.0
        //   container: "#chatroom", // DOM选择器，HTML元素，用于嵌入默认聊天室样式
        //   width: 300, // container宽度，默认300px
        //   height: "100%", // container高度，默认600px
        //   userType: "student", // 用户类型，根据实际需求设置，常用的有普通学员（student）、云课堂学员（slice）
        //   tabData: [
        //     {
        //       name: "在线",
        //       type: "user-list",
        //     },
        //   ],
        //   roomMessage: function(data) {
        //     // 聊天室消息回调函数
        //     // TODO
        //     // data为聊天室socket消息，当有聊天室消息时会触发此方法
        //     // console.log(data);
        //   },
        // });
        // 全局注册rtc
        window.rtc = new PolyvRTCWebSDK({
          roomId: vueObj.channelId,
          socket: chatroom.chat.socket, // 传入socketio实例
          userId: vueObj.userId,
          nick: vueObj.userName,
          pic: vueObj.pic
        });
        const liveSdk = new PolyvLiveSdk({
          channelId: vueObj.channelId,
          sign: vueObj.liveSign, // 频道验证签名
          timestamp: vueObj.timestamp, // 毫秒级时间戳
          appId: vueObj.appId, // polyv 后台的appId
          socket: chatroom.chat.socket,
          user: {
            userId: vueObj.userId,
            userName: vueObj.userName,
            pic: vueObj.pic
          }
        });
        liveSdk.on(PolyvLiveSdk.EVENTS.CHANNEL_DATA_INIT, (event, data) => {
          liveSdk.setupPlayer({
            el: "#player-kpb", // 讲师区域元素，也就是第 2 步中创建的 id 为 player 的元素
            type: "auto" // 根据频道实际设置自动选择播放类型
          });
        });
        vueObj.initSDK();
      },
      // 判断是否支持RTC
      supportRtc() {
        if (!PolyvRTCWebSDK.support) {
          this.$message.error('当前浏览器不支持连麦！');
        }
      },
      // 申请连麦
      joinChannel() {
        this.supportRtc();
        rtc.joinChannel();
        this.showApply = false;
        this.showCancel = true;
      },
      // 取消申请连麦
      cancelJoinChannel() {
        rtc.cancelJoinChannel();
        this.showApply = true;
        this.showCancel = false;
        this.showRTC = false;
      },
      // 挂断通话
      leaveChannel() {
        rtc.leaveChannel();
        this.showApply = true;
        this.showStop = false;
        this.showRTC = false;
      }
    }
  };
</script>
<style lang="scss">
  * {
    margin: 0;
    padding: 0;
  }
  html,
  body,
  #app {
    width: 100%;
    height: 100%;
    overflow: hidden;
  }
  .wrap {
    position: relative;
    width: 100%;
    height: 100%;
  }
  .player-main-kpb {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    // width: calc(100% - 300px);
    height: 100%;
  }
  .player-main-kpb #player-kpb {
    width: 100%;
    height: 100%;
  }
  .chat-main {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
  }
  .chat-body {
    position: relative;
    height: 100%;
    .rtc-btn {
      position: absolute;
      top: 3px;
      right: 10px;
      z-index: 9999;
    }
  }
  #chatroom {
    height: 100%;
    .polyv-chat-room ul {
      overflow: hidden;
    }
    .polyv-cr-navbar {
      padding: 0;
      li {
        display: none;
      }
      .polyv-crn-active {
        display: block;
        width: 100% !important;
        text-align: left;
        text-indent: 10px;
        cursor: default;
      }
    }
  }
  #local {
    width: 100%;
    height: 220px;
    & ~ .chat-body {
      height: calc(100% - 220px);
    }
  }
  .plv-live-player-rightMenu {
    display: none !important;
  }
  .pv-rtc-player video {
    left: 0;
  }
  .pv-rtc-controller {
    [data-type="stop"] {
      display: none;
    }
  }
  @media (orientation: landscape) {
    //横屏CSS
  }
</style>
